
import { sys } from 'cc';
import Base64 from '../encrypt/Base64';
import { StorageConfig } from "./StorageConfig";
/**
 * 本地存储管理模块
 * @author 神兽白泽
 * @description 交流群：415468592
 */
export default class StorageMgr {
    /** 本地存储用的密钥 */
    private static crypt_key: string = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    /**
     * 保存到本地
     * @param key 存储的ket
     * @param value 存储的值
     * @param encrypt 是否加密
     */
    public static set(key: keyof typeof StorageConfig, value: object, encrypt: boolean = true) {
        let str_o = JSON.stringify(value);
        let str_s = encrypt ? Base64.encode(str_o, this.crypt_key) : str_o;
        sys.localStorage.setItem(key, str_s);
    }

    /**
     * 读取本地存储
     * @param key 存储的key
     * @param decrypt 是否加密
     * @returns 
     */
    public static get(key: keyof typeof StorageConfig, decrypt: boolean = true): any {
        let value = sys.localStorage.getItem(key);
        if (!value) return value;
        try {
            if (decrypt) value = Base64.decode(value, this.crypt_key);
            value = JSON.parse(value);
            return value;
        } catch (err) {
            return value;
        }
    }
}
